package com.example.blog_system_ssm.controller;

import com.example.blog_system_ssm.common.Constant;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/admin")
public class KaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
     //获取验证码
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captcha = null;
        ByteArrayOutputStream out=new ByteArrayOutputStream();

        try {
            String createText=defaultKaptcha.createText();
            // 将生成的验证码保存在redis中
            redisTemplate.opsForValue().set(Constant.LOGIN_KAPTCHA_KEY+request.getParameter("d"),createText,3, TimeUnit.MINUTES);
            BufferedImage bi = defaultKaptcha.createImage(createText);
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captcha = out.toByteArray();
        //设置相关参数
        //配置不使用缓存，防止后端数据不更新
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        //关闭流
        sout.flush();
        sout.close();
    }
}
